package nl.project.data.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nl.project.data.Parent;
import nl.project.data.Student;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.apphosting.utils.remoteapi.RemoteApiPb.Request;

public class EnrollmentProcess extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			if (req.getSession().getAttribute("user") != null) {
				doPost(req, resp);
			} else {
				// user needs to login
				resp.sendRedirect("");
				return;
			}
		} catch (ServletException e) {
			// return something like:
			// "Something went wrong! If problem stays, contact admin!"
			resp.sendRedirect("");
			return;
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		DatastoreService d = DatastoreServiceFactory.getDatastoreService();
		// Haal de juiste ouder en student op voor de juiste info verderop
		Parent p = null;
		try {
			p = (Parent) req.getSession().getAttribute("user");
		} catch (ClassCastException e) {
			try {
				p = new Parent(Integer.parseInt(req.getSession().getAttribute("parentId").toString()));
			} catch (NumberFormatException e1) {
				resp.sendRedirect("");
			} catch (EntityNotFoundException e1) {
				resp.sendRedirect("");
			}
		}
		Student st;
		try {
			st = new Student((Integer) req.getSession().getAttribute(
					"student_id"));
		} catch (EntityNotFoundException e1) {
			// Geen studenten id gevonden. Hier is iets goed mis gegaan, stuur
			// gebruiker terug.
			resp.sendRedirect("");
			return;
		}

		// Haal de vakken op welke gekozen zijn, en split deze op per keuze
		String code = req.getParameter(("subjects"));
		// Voor het parsen van de codes verderop
		String[] tempArray = code.split("[a-zA-Z]{3},");
		// Hierin komen alle teacher codes te staan.
		ArrayList<String> teacherCodes = new ArrayList<String>();
		for (String s : tempArray) {
			if (!s.equals("")) {
				teacherCodes.add(s.substring(0, s.indexOf(";")));
			}
		}

		// Loop door alle ingestelde vakken
		for (int i = 0; i < teacherCodes.size(); i++) {
			// Maak nieuw entity om alle info in op te slaan
			Key enrollmentKey = KeyFactory.createKey("Enrollments", "Enrollments");
			Entity e = new Entity("Enrollment", enrollmentKey);

			// Er is ook een teacherId nodig, dus die zoeken we op aan de hand
			// van
			// de teacherCode (bijv. BACUL)
			Query teacherIdQuery = new Query("vak").addFilter("theacherCode",
					FilterOperator.EQUAL, teacherCodes.get(i));
			List<Entity> tl = d.prepare(teacherIdQuery).asList(
					FetchOptions.Builder.withDefaults());
			String teacherID = String.valueOf(tl.get(i).getProperty(
					"theacherID"));

			// Haal de dag op
			String day = req.getParameter("days").toString();
			ArrayList<Boolean> s = new ArrayList<Boolean>();

			if (day.equals("maandag")) {
				s.add(true);
				s.add(false);
				s.add(false);
			}
			if (day.equals("dinsdag")) {
				s.add(false);
				s.add(true);
				s.add(false);
			}
			if (day.equals("woensdag")) {
				s.add(false);
				s.add(false);
				s.add(true);
			}

			String[] addressArray = p.getAddressArray();
			String addressLine = addressArray[0];
			String addressNumber = addressArray[1];
			String zipCode = addressArray[2];
			String residence = addressArray[3];
			ArrayList<String> c = new ArrayList<String>();
			c.add((String) p.getAddressArray()[4]);
			c.add((String) addressLine + " " + addressNumber);
			c.add((String) zipCode);
			c.add((String) residence);
			c.add((String) p.getPhoneNumber());

			String time = req.getParameter("pref");

			if (time.equals("Vroeg in de avond")) {
				time = "Early";
			}
			if (time.equals("Laat in de avond")) {
				time = "Later";
			}
			if (time.equals("Geen voorkeur")) {
				time = "None";
			}

			// Voeg een voor een de kenmerken van de enrollment toe
			e.setProperty("parentID", p.getParentId());
			e.setProperty("studentID", st.getStudentId());
			e.setProperty("theacherCode", teacherCodes.get(i));
			e.setProperty("theacherID", teacherID);
			e.setProperty("days", s);
			e.setProperty("contact", c);
			e.setProperty("pref", time);
			// Einde toevoegen
			try {
				d.put(e);
				System.out.println(e.toString());
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		// Alles is gelukt, haal wat gegevens uit de sessie.
		req.getSession().setAttribute("parentId", null);
		req.getSession().setAttribute("student_id", null);
		req.getRequestDispatcher("/dashboard").forward(req, resp);
	}
}